#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2020/10/28 11:40
# @Author  : CHEN Wang
# @Site    : 
# @File    : factor_info.py
# @Software: PyCharm 

"""
脚本说明: 因子基础信息查询接口
"""

import datetime as dt
from quant_researcher.quant.project_tool.db_operator import db_conn, my_mysql

T_STOCK_FACTOR_INFO = 'stk_fac_info'
T_INDUSTRY_FACTOR_INFO = 'indu_fac_info'


def get_factor_table_name(factor, asset_type='stock'):
    """
    根据因子英文名查找股票因子对应的表名

    :param str factor: 股票因子库中的因子英文名称
    :return:
    """
    sfrom = T_STOCK_FACTOR_INFO if asset_type=='stock' else T_INDUSTRY_FACTOR_INFO
    conn = db_conn.get_tk_factors_conn()
    factor_table_info = my_mysql.read_v2(sfrom=sfrom,
                                         select=['factor_table_name', 'factor_name_cn'],
                                         where=f"factor_name_en = '{factor}'",
                                         conn=conn)
    if factor_table_info.empty:
        print('请检查因子名称是否正确。目前库里没有该因子')
        factor_table_name = None
        factor_name_cn = None
    else:
        factor_table_name = factor_table_info.iloc[0, 0]
        factor_name_cn = factor_table_info.iloc[0, 1]

    conn.close()

    return factor_table_name, factor_name_cn


def get_factor_start_end(factor):
    """
    根据因子英文名查找因子数据的起始时间和结束时间

    :param str factor: 股票因子库中的因子英文名称
    :return:
    """

    conn = db_conn.get_tk_factors_conn()
    factor_table_name, _ = get_factor_table_name(factor)
    date_df = my_mysql.read_v2(sfrom=factor_table_name,
                               select=['min(tradedate)', 'max(tradedate)'], conn=conn)
    start_date = dt.datetime.strftime(date_df.iloc[0, 0], '%Y-%m-%d')
    end_date = dt.datetime.strftime(date_df.iloc[0, 1], '%Y-%m-%d')

    conn.close()

    return start_date, end_date


if __name__ == '__main__':
    factor = 'cetop'
    # 测试get_factor_table_name
    # factor_table_name, factor_name_cn = get_factor_table_name(factor)

    # 测试get_factor_start_end
    start, end = get_factor_start_end(factor)
